<?php
class ImagesController extends AppController {

	var $name = 'Images';
	var $helpers = array('Html','Form','Accessibility','Pagination', 'Associations','Input');
	var $uses = array('Image','Configuration');
	var $components = array('Upload');
	
	/*
	function upload() {

		if (empty($this->data)) {
			$this->render();
		} else {
			$this->cleanUpFields();

			// set the upload destination folder
			$destination = realpath('../../app/webroot/img/uploads/') . '/';

			// grab the file
			$file = $this->data['Image']['filedata'];

			// upload the image using the upload component
			$result = $this->Upload->upload($file, $destination, null, array('type' => 'resizecrop', 'size' => array('400', '300'), 'output' => 'jpg'));

			if (!$result){
				$this->data['Image']['images'] = $this->Upload->result;
			} else {
				// display error
				$errors = $this->Upload->errors;
   
				// piece together errors
				if(is_array($errors)){ $errors = implode("<br />",$errors); }
   
					$this->Session->setFlash($errors);
					$this->redirect('/images/upload');
					exit();
				}
			if ($this->Image->save($this->data)) {
				$this->Session->setFlash('Image has been added.');
				$this->redirect('/images/index');
			} else {
				$this->Session->setFlash('Please correct errors below.');
				unlink($destination.$this->Upload->result);
			}
		}
	}
	*/

	function upload($album_id = null) 
		{	
			// Retrieving organization's data 
			$organization = $this->othAuth->getData('organization');

	   	if (empty($this->data)) 
			{
				if(!$album_id)
				{
						// Redirecting to File List     
						$_SESSION['mensagem']['error'][] = 'Álbum inválido!';       
						$this->redirect('/webs/albuns');
				}

				$title = 'Adicionar imagem';
				$this->set('title', $title);
				$this->set('pageTitle', $title);

				$this->data['Image']['album_id'] = $album_id;

			}
			else
			{ 		
				if (is_uploaded_file($this->data['Image']['File']['tmp_name'])) 
				{
					/* checking quota */
					$sum = $this->Image->find('all', array('fields'=>array('SUM(tamanho) AS total_sum'),
			                                      'conditions'=>array('Image.organization_id'=>$organization['id']),
			                                      'recursive'=>-1));
					$used = ($sum[0][0]['total_sum']);
				
					$configuration_quota = $this->Configuration->find('first', array('conditions'=>array('name'=>'download_quota')));
					$quota = ($configuration_quota['Configuration']['value']);
				
					if (($used + $this->data['Image']['File']['size']) > $quota) 
					{
						$_SESSION['mensagem']['error'][] = 'Quota estourada.';
					}
					
					$file = $this->data['Image']['File'];
				
					// Retrieving data from uploaded file
					$size = $this->data['Image']['File']['size'];
					 	
					// Getting file extension
					$extensions = explode(".",$this->data['Image']['File']['name']);
					$extension = $extensions[sizeof($extensions)-1];

				
					// Generating file's path and name
					$path = '/cms/'.$organization['id'];
					$filename = $this->data['Image']['File']['name'].'.'.$extension;

					// set the upload destination folder
					$destination = realpath('../../app/webroot/') . $path.'/';

					// 	Creating folder for organization
					if(!is_dir($destination)) 
					{
						mkdir($destination, 0777);
					}
				
					if (!isset($_SESSION['mensagem']['error'])) 
					{

						// upload the image using the upload component
						$result = $this->Upload->upload($file, $destination, $this->data['Image']['File']['name'], NULL, array('*'));
			
						// Creating information about created file				
							//$this->data['Image']['type'] = $this->data['Image']['File']['type'];
							$this->data['Image']['tamanho'] = $this->data['Image']['File']['size'];
							$this->data['Image']['filename'] = $path."/".$this->data['Image']['File']['name'];
							//$this->data['Image']['data'] 				= $fileData;
							$this->data['Image']['organization_id'] = $organization['id'];
		
						// Saving information on database
						$this->Image->save($this->data);
		
						// Redirecting to File List     
						$_SESSION['mensagem']['success'][] = 'Imagem adicionada com sucesso!';       
						$this->redirect('/albums/view/'.$this->data['Image']['album_id']);
					} 
				} 
				else 
				{
					// Display "Invalid File" error message
				}
			}

		}


		function show($id)
		{			
				if(!$id)
				{
						// Redirecting to File List     
						$_SESSION['mensagem']['error'][] = 'Imagem inválida!';       
						$this->redirect('/webs/albuns');
				}
				
				$title = 'Visualizar imagem';
				$this->set('title', $title);
				$this->set('pageTitle', $title);
	

				$this->Image->id = $id;
				$image = $this->Image->read();
				$this->set('image',$image);
				
		}


		function edit($id)
		{
				if (!$id)
				{
					$this->redirect('/webs/albuns');
				}
		
				$this->set('pageTitle','Editar Imagem');
				$this->Image->id = $id;

				if (empty($this->data)) {
					$this->data = $this->Image->read();
				}
				else 
				{

					if ($this->Image->save($this->data['Image'])) 
					{
						$_SESSION['mensagem']['success'][] = 'Foto alterada com sucesso!';
					} 
					else 
					{
						$_SESSION['mensagem']['error'][] = 'Erro ao tentar alterar a Foto.';
					}
					$this->redirect('/images/show/'.$id);
				}
				$image = $this->Image->find(array('`Image`.id' => $id));
				$this->set('image', $image);
		}

	function delete($id=NULL) {
		if (!$id) $this->redirect('/webs/albuns');
		
		$image = $this->Image->find(array('`Image`.id' => $id));
		$path = $image['Image']['filename'];
		$album_id = $image['Image']['album_id'];
		$destination = realpath('../../app/webroot/') . $path;
		
		if ($this->Image->del($id)) {
			if (unlink($destination)) {	
				$_SESSION['mensagem']['success'][] = 'Imagem excluida com sucesso!';

			} else {
				$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir a imagem.';
			}
		} else {
			$_SESSION['mensagem']['error'][] = 'Erro ao tentar excluir a imagem.';
		}
		$this->redirect('/albums/view/'.$album_id);
	}
	


}
?>
